<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdminController  extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('admin.admin.index');
    }

    public function adminList()
    {
        $list = DB::table('admins')
            ->orderBy('id', 'desc')
            ->get();
        return successResp($list);
    }

    public function save(Request $request, $id)
    {
        //验证表单
        $this->validate($request, [
            'username' => ['required','string', 'max:16'],
            'password' => ['string'],
            'role' => ['required','int'],
        ]);
        $data = [
            'username' => $request->username,
            'role' => $request->role,
        ];
        if($id != 0){
            // 更新
            DB::table('admins')
                ->where('id', $id)
                ->update($data);
        }else{
            if (empty($request->password)) {
                $request->password = '123456';
            }
            $data['password'] = Hash::make($request->password);
            // 创建
            DB::table('admins')
                ->insert($data);
        }
        return successResp('');
    }

    public function destroy(Request $request)
    {
        $id = $request->id;
        if (!$id) {
            return errorResp('id empty');
        }
        DB::table('admins')
            ->where('id',$id)
            ->delete();
        return successResp('');
    }
}
